package com.byron.media.server.sessions;

import com.byron.media.server.config.MediaServerConfig;
import com.byron.media.server.enums.Args;
import com.byron.media.server.model.MediaData;
import com.byron.media.server.model.MediaHeaderObj;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;

/**
 * 直接面向终端的session
 */
@Slf4j
public class ClientSession implements ISession {

    // 真实的连接
    private RealSession realSession;

    // 连接的唯一标识
    private String device;

    // 组名字
    private String groupName;

    // 是否已激活
    private boolean active;

    private long sessionName;     // 连接名字

    private Group group;            // 连接所在组

    private byte serverId;

    private String remoteAddress;

    private String sessionId;

    private MediaServerConfig config;

    public ClientSession(RealSession realSession) {
        this.realSession = realSession;
        this.config = MediaServerConfig.getInstance();
    }

    @Override
    public void write(byte lastServerId, long fromSessionName, MediaData data) {
        if(realSession != null){
            realSession.write(data);
        }
    }

    @Override
    public String getDevice() {
        return device;
    }

    @Override
    public String getGroupName() {
        return groupName;
    }

    @Override
    public long getSessionName() {
        return sessionName;
    }

    @Override
    public boolean isActive() {
        return active;
    }

    @Override
    public void inactive() {
        group.removeFromGroup(sessionName, this);
        if(config.isLog()){
            log.info("客户端【{}】掉线", realSession.getClientSession().toString());
            log.error("客户端【{}】掉线", realSession.getClientSession().toString());
        }

        MediaHeaderObj header = new MediaHeaderObj();
        header.getCmd().put("cmd", "unreg");
        header.getDevice().put("id", device);
        header.getArgs().put(Args.SESSION_NAME, sessionName + "");

        SessionContainer.getInstance().sendToProxyServer(header);
    }

    @Override
    public void sendToOther(MediaData mediaData) {
        group.sendToOthers(serverId, sessionName, mediaData);
    }

    @Override
    public void active(MediaHeaderObj header) {
        if(active){
            return;
        }

        String groupName = (String) header.getArgs().get(Args.GROUP_NAME);
//        boolean sender = (boolean) header.getArgs().getOrDefault(Args.SENDER, false);
        String device = (String) header.getDevice().get("id");        // 是否从代理服务器中发送

        this.groupName = groupName;
        this.device = device;
        this.sessionName = RandomUtils.nextLong();
        this.serverId = MediaServerConfig.getInstance().getServerId();
        SessionContainer.getInstance().sendLastIframe(groupName, this);
        this.group = SessionContainer.getInstance().addToGroup(sessionName, groupName, this);
        this.active = true;
        this.realSession.activeAsClient(this);
        this.remoteAddress = realSession.getChannel().remoteAddress().toString();


        // 同时把json发到其他代理服务器
        header.getArgs().put(Args.SESSION_NAME, sessionName + "");
        SessionContainer.getInstance().sendToProxyServer(header);

        if(config.isLog()){
            log.info("流媒体客户端 " + device + " 连接成功");
        }
    }

    @Override
    public String toString() {
        return "ClientSession{" +
                "device='" + device + '\'' +
                ", remoteAddress='" + remoteAddress + '\'' +
                '}';
    }
}
